package com.spring5.learning.strategy;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author xin
 * @version 1.0
 */
@Component
public class MemberStrategyContext implements InitializingBean {

    @Autowired
    private List<CalculatePriceStrategy> strategies;

    private Map<MemberType, CalculatePriceStrategy> map = new HashMap<>();


    public CalculatePriceStrategy strategy(MemberType type) {
        return map.get(type);
    }

    public BigDecimal calculate(MemberType type) {
        CalculatePriceStrategy strategy = strategy(type);
        if (strategy != null) {
            return strategy.calculate();
        }
        return null;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        strategies.forEach(strategy -> map.put(strategy.getMemberType(), strategy));
    }
}
